/**
 * Copyright (C) 2017 - 2020 https://github.com/joewee
 * <p>
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * <p>
 * http://www.apache.org/licenses/LICENSE-2.0
 * <p>
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.bifrost.wechat.controller;

import com.bifrost.common.util.HttpRequestUtils;
import com.bifrost.wechat.service.WxServiceContext;
import me.chanjar.weixin.common.bean.menu.WxMenu;
import me.chanjar.weixin.common.bean.menu.WxMenuButton;
import me.chanjar.weixin.common.exception.WxErrorException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;

/**
 * @author bifrost
 * @version 1.0.0
 * @Date 2017/10/18 10:18
 */
@RestController
@RequestMapping("wechat/menu")
public class WechatMenuController {
    @Autowired
    WxServiceContext context;
    @RequestMapping("/init/{id}")
    public String initMenu(@PathVariable("id")String appid, HttpServletRequest request) {
        if (appid != null) {
            try {
                WxMenu menu = new WxMenu();
                WxMenuButton button = new WxMenuButton();
                button.setName("微商城");
                button.setType("view");
                button.setUrl(String.format("%s/index/%s", HttpRequestUtils.getApplicationContext(request),appid));
                List<WxMenuButton> buttons = new ArrayList<WxMenuButton>();
                buttons.add(button);
                menu.setButtons(buttons);
                return context.getWxServiceByAppId(appid).getMenuService().menuCreate(menu);
            } catch (WxErrorException e) {
                e.printStackTrace();
            }
        }
        return "{code:500,msg:\"发生错误\"}";
    }
}
